#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: release_requirements_or_bug_infor.py
# Author: ChenChangSong
# Date: 2025-08-24

"""
功能描述: 发布需求或bug信息
"""
from math import e, log
from pdb import run
from datetime import datetime

import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent.parent.parent))

from comm.common_code import *
from comm.common_code import get_excel_data, logger, log_to_ui_info, log_to_ui_error

from tapd_capture_api.requirements.get_workflow_info import req_get_workflow_info
from tapd_capture_api.bug.bug_get_workflow_info import bug_get_workflow_info

def release_requirements_or_bug_info():
    """发布需求或bug信息"""
    excel_data = get_excel_data()


    # 获取今日日期
    today = datetime.now()

    # 格式化为所需字符串
    start_time = today.strftime("%Y-%m-%d 00:00")
    end_time = today.strftime("%Y-%m-%d 23:59")
    today_time = f"{start_time},{end_time}" # "2025-09-04 00:00,2025-09-04 23:59"
    # today_time ="2025-11-03 00:00,2025-11-03 23:59"

    requirements_info = f"今日：{today_time} ：\n今日发布需求：\n"
    bugs_info = "BugFix：\n"
    # ==================================需求======================================
    url = "https://www.tapd.cn/api/entity/stories/stories_list"
    payload = json.dumps({
    "exclude_workspace_configs": [],
    "workspace_id": f"{excel_data["项目ID"]}",
    "category_id": "0",
    # "query_token": "aab37fd473cbc19f6ccba25d6265dc91",
    "list_type": "tree",
    "conf_id": "1166606973001129840",
    "confIdType": "URL",
    "sort_name": "sort",
    "order": "",
    "perpage": 100,
    "page": 1,
    "need_category_counts": 1,
    "entity_types": [
        "story"
    ],
    "selected_workspace_ids": [
        f"{excel_data["项目ID"]}"
    ],
    "location": "/prong/stories/stories_list",
    "menu_workitem_type_id": "",
    "identifier": "app_for_list_tools,app_for_list_operation",
    "hide_not_match_condition_sub_node": 1,
    "block_type": "",
    "block_size": 20,
    "primary_data_only": False,
    "app_id": "",
    "useScene": "storyList",
    "filter_data": {
        "filter_expr": {
        "data": [
            {
            "fieldOption": "between",
            "fieldType": "dateinput",
            "entity": "story",
            "fieldSubValue": "",
            "fieldSystemName": "需求实际发版时间",
            "fieldDisplayName": "需求实际发版时间",
            "selectOption": [],
            "value": today_time,#"value": "2025-09-03 00:00,2025-09-03 23:59"
            "fieldIsSystem": "0"
            }
        ],
        "optionType": "AND",
        "needInit": True
        },
        "filter_type": "base"
    },
    "dsc_token": "EegFkOGYWhq50vpT"
    })
    headers = {
    'authority': 'www.tapd.cn',
    'accept': 'application/json, text/plain, */*',
    'accept-language': 'zh-CN,zh;q=0.9',
    'content-type': 'application/json',
    'cookie': excel_data['Cookie'],
    'origin': 'https://www.tapd.cn',
    # 'referer': 'https://www.tapd.cn/tapd_fe/66606973/story/list?categoryId=0&useScene=storyList&groupType=&conf_id=1166606973001129840&queryToken=aab37fd473cbc19f6ccba25d6265dc91&page=1',
    'sec-ch-ua': '"Not)A;Brand";v="24", "Chromium";v="116"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-origin',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.559.400 QQBrowser/19.6.6683.400'
    }
    # requirements_release_status = {'resolved': '内测完成','status_1': '已合代码','status_10': '发车测试中', 'status_11': '发车测试完成', 'status_2': '上Alpha测试', 'status_3': 'Alpha已通过', 'status_7': 'Beta已通过', 'status_16': '灰度上线', 'status_4': '已上线', 'status_5': '已验收'}
    requirements_release_status = req_get_workflow_info()
    response_code, response = api_request(method="POST", url=url, headers=headers, data=payload)
    new_req_id_and_url = {}
    new_req_id_and_name = {}
    new_req_id_and_tester = {}
    new_req_id_and_status = {} 
    # logger.info(f'响应内容{response}')
    if response_code == 200:
        stories_list = response['data']['stories_list']
        for i, story in enumerate(stories_list):
            print("ccs",story)
            story_id = story['Story']['id'] # 需求ID
            story_name = story['Story']['name'] # 需求名称
            status = story['Story']['status']   # 需求状态
            try:
                custom_field1 = story['Story']['custom_field_two'] # 测试人员2
            except:
                custom_field1 = story['Story']['custom_field_测试人员'] # 测试人员
            # custom_field_two = story['Story']['custom_field_two']# 测试人员2
            new_req_id_and_status[story_id] = status
            new_req_id_and_name[story_id] = story_name
            new_req_id_and_tester[story_id] = custom_field1
            new_req_id_and_url[story_id] = f'https://www.tapd.cn/tapd_fe/{excel_data["项目ID"]}/story/detail/{story_id}'
            requirements_info += f"\t{i+1}、【 {story_name}】\n\t{new_req_id_and_url[story_id]}\n"
 
        # 获取状态顺序列表（基于requirements_release_status的键顺序）
        req_status_order = list(requirements_release_status.keys())

        # 初始化最高和最低状态索引
        req_max_index = -1
        req_min_index = len(req_status_order)  # 初始化为最大值
        req_max_status_key = None
        req_min_status_key = None

        # 遍历new_req_id_and_status中的状态值
        for status_key in new_req_id_and_status.values():
            # 获取当前状态键在顺序列表中的索引
            index = req_status_order.index(status_key)
            
            # 更新最高状态
            if index > req_max_index:
                req_max_index = index
                req_max_status_key = status_key
                
            # 更新最低状态
            if index < req_min_index:
                req_min_index = index
                req_min_status_key = status_key
    else:
        logger.info(f"请求失败，状态码：{response_code}")
        return
    # =================bug信息=========================
    url = "https://www.tapd.cn/api/entity/bugs/bugs_list"

    payload = json.dumps({
    "workspace_id": excel_data['项目ID'],
    "conf_id": "1166606973001130022",
    "sort_name": "",
    "confIdType": "CACHE",
    "order": "desc",
    "perpage": 100,
    "page": 1,
    "selected_workspace_ids": [
        excel_data['项目ID']
    ],
    "filter_expr": {
        "data": [
        {
            "fieldOption": "like",
            "fieldType": "input",
            "entity": "bug",
            "fieldSystemName": "name",
            "fieldDisplayName": "标题",
            "selectOption": [],
            "value": "",
            "fieldIsSystem": "1"
        },
        {
            "fieldOption": "between",
            "fieldType": "dateinput",
            "entity": "bug",
            "fieldSubValue": "",
            "fieldSystemName": "due",
            "fieldDisplayName": "预计结束",
            "selectOption": [],
            "value": today_time,#"2025-09-04,2025-09-04"
            "fieldIsSystem": "1"
        }
        ],
        "optionType": "AND",
        "needInit": True
    },
    "return_url": f"https://www.tapd.cn/tapd_fe/{excel_data['项目ID']}/bug/list",
    "main_location": "",
    "location": "",
    "show_fields": [],
    "exclude_workspace_configs": [],
    "dsc_token": "EegFkOGYWhq50vpT"
    })
    headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'Content-Type': 'application/json',
    'Cookie': excel_data['Cookie'],
    'Origin': 'https://www.tapd.cn',
    # 'Referer': f'https://www.tapd.cn/tapd_fe/{excel_data["项目ID"]}/bug/list?confId=116{excel_data["项目ID"]}001130022&queryToken=cb15f3daf673d07f043b7ec28e540ce9&sort_name=&order=desc&displayEmptyGroup=display&groupType=&page=1',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.559.400 QQBrowser/19.6.6683.400',
    'sec-ch-ua': '"Not)A;Brand";v="24", "Chromium";v="116"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"'
    }

    # bug_release_status = {
    #  'verified': '内测完成','PMM_audited': '已合代码', 'unconfirmed': '发车测试中', 'assigned': '发车测试完成',
    #  'TM_audited': '上alpha测试', 'QA_audited': 'alpha已通过', 'acknowledged': 'Beta已通过', 'closed': '已修复上线', }
    bug_release_status = bug_get_workflow_info()
    response_code, response = api_request(method="POST", url=url, headers=headers, data=payload)
    no_change_req_and_bug = '\n' # 未改需求和bug状态的信息
    new_bug_id_and_status = {}
    new_bug_id_and_url = {}
    new_bug_id_and_name = {}
    new_bug_id_and_tester = {}
    # logger.info(response)
    if response_code == 200:
        bugs_list = response["data"]["bugs_list"]
        for j,bug in enumerate(bugs_list):
            bug_id = bug["Bug"]["id"]
            bug_title = bug["Bug"]["title"]
            bug_tester = bug["Bug"]["te"]
            bug_status = bug["Bug"]["status"]
            bug_url = f"https://www.tapd.cn/tapd_fe/{excel_data['项目ID']}/bug/detail/{bug_id}"
            new_bug_id_and_status[bug_id] = bug_status
            new_bug_id_and_url[bug_id] = bug_url
            new_bug_id_and_name[bug_id] = bug_title
            new_bug_id_and_tester[bug_id] = bug_tester
            bugs_info += f"\t{j+1}、【 {bug_title}】\n\t{bug_url}\n"
        # 获取状态顺序列表（基于bug_release_status的键顺序）
        bug_status_order = list(bug_release_status.keys())

        # 初始化最高和最低状态索引
        bug_max_index = -1
        bug_min_index = len(bug_status_order)  # 初始化为最大值
        bug_max_status_key = None
        bug_min_status_key = None

        # 遍历new_bug_id_and_status中的状态值
        for status_key in new_bug_id_and_status.values():
            # 获取当前状态键在顺序列表中的索引
            index = bug_status_order.index(status_key)
            
            # 更新最高状态
            if index > bug_max_index:
                bug_max_index = index
                bug_max_status_key = status_key
                
            # 更新最低状态
            if index < bug_min_index:
                bug_min_index = index
                bug_min_status_key = status_key
    else:
        logger.error("获取bug信息失败")
        return

    logger.info(f"\n{requirements_info}\n{bugs_info}")
    log_to_ui_info(f"\n{requirements_info}\n{bugs_info}")

    logger.info(f'↑↑↑=================================================↑↑↑')
    # ================需求最进展====================
    if new_req_id_and_status:
        # 检查最高状态和最低状态是否相同
        if req_max_status_key == req_min_status_key and (req_min_status_key == 'status_16' or req_min_status_key == 'status_4' or req_min_status_key == 'status_5'):#最低状态 '灰度上线'、'已上线'、'已验收'
            logger.info("所有需求状态相同，且已上线，无需显示最高和最低状态")
            log_to_ui_info("所有需求状态相同，且已上线，无需显示最高和最低状态")
        else:
            # 获取最高和最低状态对应的名称
            max_status_name = requirements_release_status[req_max_status_key]
            min_status_name = requirements_release_status[req_min_status_key]
            
            # logger.info(f"需求最高状态键: {req_max_status_key}")
            logger.info(f"需求最高状态名称: {max_status_name}")
            log_to_ui_info(f"需求最高状态名称: {max_status_name}")
            # logger.info(f"需求最低状态键: {req_min_status_key}")
            logger.info(f"需求最低状态名称: {min_status_name}")
            log_to_ui_info(f"需求最低状态名称: {min_status_name}")
        if req_max_status_key == 'resolved': #'内测完成'
            logger.info(f'@所有人 今天发布的需求请修改需求状态！')
            log_to_ui_info(f'@所有人 今天发布的需求请修改需求状态！')
        elif req_max_status_key == 'status_1': #'已合代码'
            # @状态是resolved的需求的人员改状态
            for story_id, status in new_req_id_and_status.items():
                if status == 'resolved':
                    tester = new_req_id_and_tester[story_id]
                    no_change_req_and_bug += f'@{tester} 需求 【{new_req_id_and_name[story_id]}】 请合代码\n'
        elif req_max_status_key == 'status_10': #'发车测试中'
            # @状态是resolved、status_1的需求的人员改状态
            for story_id, status in new_req_id_and_status.items():
                if status == 'resolved' or status == 'status_1': 
                    tester = new_req_id_and_tester[story_id]
                    no_change_req_and_bug += f'@{tester} 需求 【{new_req_id_and_name[story_id]}】 请及更新状态\n'
        elif req_max_status_key == 'status_11': #'发车测试完成'
            # @状态是resolved、status_1、status_10的需求的人员改状态
            for story_id, status in new_req_id_and_status.items():
                if status == 'resolved' or status == 'status_1' or status == 'status_10':
                    tester = new_req_id_and_tester[story_id]                
                    no_change_req_and_bug += f'@{tester} 需求 【{new_req_id_and_name[story_id]}】 请及更新状态\n'
        elif req_max_status_key == 'status_2': #'上Alpha测试'
            # @状态是resolved、status_1、status_10、status_11的需求的人员改状态
            for story_id, status in new_req_id_and_status.items():
                if status == 'resolved' or status == 'status_1' or status == 'status_10' or status == 'status_11':
                    tester = new_req_id_and_tester[story_id]
                    no_change_req_and_bug += f'@{tester} 需求 【{new_req_id_and_name[story_id]}】 请及更新状态\n'
        elif req_max_status_key == 'status_3': #'Alpha已通过'
            # @状态是resolved、status_1、status_10、status_11、status_2的需求的人员改状态
            for story_id, status in new_req_id_and_status.items():
                if status == 'resolved' or status == 'status_1' or status == 'status_10' or status == 'status_11' or status == 'status_2':
                    tester = new_req_id_and_tester[story_id]
                    no_change_req_and_bug += f'@{tester} 需求 【{new_req_id_and_name[story_id]}】 请及更新状态\n'
        elif req_max_status_key == 'status_7': #'Beta已通过'
            # @状态是resolved、status_1、status_10、status_11、status_2、status_3的需求的人员改状态
            for story_id, status in new_req_id_and_status.items():
                if status == 'resolved' or status == 'status_1' or status == 'status_10' or status == 'status_11' or status == 'status_2' or status == 'status_3':
                    tester = new_req_id_and_tester[story_id]
                    no_change_req_and_bug += f'@{tester} 需求 【{new_req_id_and_name[story_id]}】 请及更新状态\n'
        elif req_max_status_key == 'status_16' or req_max_status_key == 'status_4' or req_max_status_key == 'status_5': #'灰度上线'、'已上线'、'已验收'
            # @状态是resolved、status_1、status_10、status_11、status_2、status_3、status_7的需求的人员改状态
            for story_id, status in new_req_id_and_status.items():
                if status == 'resolved' or status == 'status_1' or status == 'status_10' or status == 'status_11' or status == 'status_2' or status == 'status_3' or status == 'status_7':
                    tester = new_req_id_and_tester[story_id]
                    no_change_req_and_bug += f'@{tester} 需求 【{new_req_id_and_name[story_id]}】 有人完成线上测试，请及测试并更新状态\n'
        # @最低状态的人员改状态
        for story_id, status in new_req_id_and_status.items():
            if status == req_min_status_key and req_min_status_key != 'status_16' and req_min_status_key != 'status_4' and req_min_status_key != 'status_5':#最低状态非 '灰度上线'、'已上线'、'已验收'
                tester = new_req_id_and_tester[story_id]
                no_change_req_and_bug += f'@{tester} 需求 【{new_req_id_and_name[story_id]}】 拖节奏啦，请及更新状态\n'

        
    
    # ================bug最进展====================
    if new_bug_id_and_status:
        # 检查最高状态和最低状态是否相同
        if bug_max_status_key == bug_min_status_key and (bug_min_status_key == 'status_16' or bug_min_status_key == 'status_4' or bug_min_status_key == 'status_5'):#最低状态 '灰度上线'、'已上线'、'已验收'
            logger.info("所有bug状态相同，且已上线，无需显示最高和最低状态")
            log_to_ui_info("所有bug状态相同，且已上线，无需显示最高和最低状态")
        else:
            # 获取最高和最低状态对应的名称
            max_status_name = bug_release_status[bug_max_status_key]
            min_status_name = bug_release_status[bug_min_status_key]
            
            # logger.info(f"bug最高状态键: {bug_max_status_key}")
            logger.info(f"bug最高状态名称: {max_status_name}")
            log_to_ui_info(f"bug最高状态名称: {max_status_name}")
            
            # logger.info(f"bug最低状态键: {bug_min_status_key}")
            logger.info(f"bug最低状态名称: {min_status_name}")
            log_to_ui_info(f"bug最低状态名称: {min_status_name}")
        if bug_max_status_key == 'verified': #'内测完成'
            logger.info(f'@所有人 今天发布的bug请修改bug状态！')
            log_to_ui_info(f'@所有人 今天发布的bug请修改bug状态！')
        elif bug_max_status_key == 'PMM_audited': #'已合代码'
            # @状态是verified的bug的人员改状态
            for bug_id, status in new_bug_id_and_status.items():
                if status == 'verified':
                    tester = new_bug_id_and_tester[bug_id]
                    no_change_req_and_bug += f'@{tester} bug 【{new_bug_id_and_name[bug_id]}】 请合代码\n'
        elif bug_max_status_key == 'unconfirmed': #'发车测试中'
            # @状态是verified、PMM_audited的bug的人员改状态
            for bug_id, status in new_bug_id_and_status.items():
                if status == 'verified' or status == 'PMM_audited': 
                    tester = new_bug_id_and_tester[bug_id]
                    no_change_req_and_bug += f'@{tester} bug 【{new_bug_id_and_name[bug_id]}】 请及更新状态\n'
        elif bug_max_status_key == 'assigned': #'发车测试完成'
            # @状态是verified、PMM_audited、unconfirmed的bug的人员改状态
            for bug_id, status in new_bug_id_and_status.items():
                if status == 'verified' or status == 'PMM_audited' or status == 'unconfirmed':
                    tester = new_bug_id_and_tester[bug_id]
                    no_change_req_and_bug += f'@{tester} bug 【{new_bug_id_and_name[bug_id]}】 请及更新状态\n'
        elif bug_max_status_key == 'TM_audited': #'上Alpha测试'
            # @状态是verified、PMM_audited、unconfirmed、assigned的bug的人员改状态
            for bug_id, status in new_bug_id_and_status.items():
                if status == 'verified' or status == 'PMM_audited' or status == 'unconfirmed' or status == 'assigned':
                    tester = new_bug_id_and_tester[bug_id]
                    no_change_req_and_bug += f'@{tester} bug 【{new_bug_id_and_name[bug_id]}】 请及更新状态\n'
        elif bug_max_status_key == 'QA_audited': #'Alpha已通过'
            # @状态是verified、PMM_audited、unconfirmed、assigned、TM_audited的bug的人员改状态
            for bug_id, status in new_bug_id_and_status.items():
                if status == 'verified' or status == 'PMM_audited' or status == 'unconfirmed' or status == 'assigned' or status == 'TM_audited':
                    tester = new_bug_id_and_tester[bug_id]
                    no_change_req_and_bug += f'@{tester} bug 【{new_bug_id_and_name[bug_id]}】 请及更新状态\n'
        elif bug_max_status_key == 'acknowledged': #'Beta已通过'
            # @状态是verified、PMM_audited、unconfirmed、assigned、TM_audited、QA_audited的bug的人员改状态
            for bug_id, status in new_bug_id_and_status.items():
                if status == 'verified' or status == 'PMM_audited' or status == 'unconfirmed' or status == 'assigned' or status == 'TM_audited' or status == 'QA_audited':
                    tester = new_bug_id_and_tester[bug_id]
                    no_change_req_and_bug += f'@{tester} bug 【{new_bug_id_and_name[bug_id]}】 请及更新状态\n'
        elif bug_max_status_key == "closed": #已修复上线
            # @状态是verified、PMM_audited、unconfirmed、assigned、TM_audited、QA_audited、acknowledged的bug的人员改状态
            for bug_id, status in new_bug_id_and_status.items():
                if status == 'verified' or status == 'PMM_audited' or status == 'unconfirmed' or status == 'assigned' or status == 'TM_audited' or status == 'QA_audited' or status == 'acknowledged':
                    tester = new_bug_id_and_tester[bug_id]
                    no_change_req_and_bug += f'@{tester} bug 【{new_bug_id_and_name[bug_id]}】 有人完成线上测试，请及测试并更新状态\n'
        # @最低状态的人员改状态
        for bug_id, status in new_bug_id_and_status.items():
            if status == bug_min_status_key and bug_min_status_key != "closed":#已修复上线
                tester = new_bug_id_and_tester[bug_id]
                no_change_req_and_bug += f'@{tester} bug 【{new_bug_id_and_name[bug_id]}】 拖节奏啦，请及更新状态\n'

    no_change_req_and_bug = no_change_req_and_bug.replace('；', '').replace(';', '')
    logger.info(no_change_req_and_bug)
    log_to_ui_info(no_change_req_and_bug)
if __name__ == '__main__':
    release_requirements_or_bug_info()
